﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WebSocketSharp.Server;

namespace WbSocket.Winform
{
    public partial class Form1 : Form
    {
        private HttpServer httpsv;
        public Form1()
        {
            InitializeComponent();
            httpsv = new HttpServer(4649);
            httpsv.DocumentRootPath = ConfigurationManager.AppSettings["DocumentRootPath"];
            httpsv.OnGet += Httpsv_OnGet;
            httpsv.AddWebSocketService<Echo>("/Echo");
            httpsv.AddWebSocketService<Chat>("/Chat");
        }

        private void Httpsv_OnGet(object sender, HttpRequestEventArgs e)
        {
            BaseRequest req = BaseRequest.Create(e);
            byte[] contents = req?.GetResponseContent();
            if (contents != null)
            {
                e.Response.ContentLength64 = contents.LongLength;
                e.Response.Close(contents, true);
            }
        }

        private void btnChat_Click(object sender, EventArgs e)
        {
            httpsv.WebSocketServices["/Chat"].Sessions.Broadcast($"Chat:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
        }

        private void btnEcho_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            httpsv.Start();
            if (httpsv.IsListening)
            {
                Console.WriteLine($"Listening on port 【{httpsv.Port}】, and providing WebSocket services:【{httpsv.DocumentRootPath}】");

                foreach (var path in httpsv.WebSocketServices.Paths)
                    Console.WriteLine("- {0}", path);
            }
            //httpsv.Stop();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            httpsv.Stop();
        }
    }
}
